import json
import platform
import os
import sys
from flask import Blueprint, current_app, request
from loguru import logger
from sqlalchemy.orm import class_mapper
import pymysql


# vscode 用
if platform.system() == 'Windows':
    env_path = os.path.dirname(os.path.abspath(__file__)).split("\\python")[0] + "\\python\\com"
    print(env_path)
    sys.path.append(os.path.dirname(env_path))
elif platform.system() == 'Linux':
    env_path = os.path.relpath(__file__).split("python")[0] + "python/com"
    print(env_path)
    sys.path.append(os.path.dirname(env_path))

# pycharm 识别不到，就把python目录设为root目录，再重新打开
from com.wenzhi.soft.db.local_db import app, db
from com.wenzhi.soft.model.soft_model import TbSoft


pymysql.install_as_MySQLdb()

soft_blue = Blueprint('soft', __name__)
print(soft_blue)

with app.app_context():
    # 放这儿报错的！
    # app.register_blueprint(soft_blue, url_prefix='/soft')
    # 输出要用with
    print(app)
    print(current_app)


def to_dict(obj):
    results = []
    for result in obj:
        mapper = class_mapper(result.__class__)
        results.append({column.key: str(getattr(result, column.key))
                        if getattr(result, column.key) != None else ""
                        for column in mapper.columns})
    logger.info(f"results::::::::::::::::::{results}")
    return results

@soft_blue.route('/query', methods=['GET', 'POST'])
def query_soft():
    try:
        if request.method == "POST":
            data = request.get_json()
            current_page = data.get("current") if data.get("current") else 1
            per_page = data.get("pageSize") if data.get("pageSize") else 20
            print(f"current_page: {current_page}")
            print(f"per_page: {per_page}")
            # 模糊查询
            soft_id = data.get("soft_id") if data.get("soft_id") else ""
            soft_name = data.get("soft_name") if data.get("soft_name") else ""
            soft_version = data.get("soft_version") if data.get("soft_version") else ""
            git_url = data.get("git_url") if data.get("git_url") else ""
            official_url = data.get("official_url") if data.get("official_url") else ""
            main_language = data.get("main_language") if data.get("main_language") else ""
            languages = data.get("languages") if data.get("languages") else ""
            start_time = data.get("startTime") if data.get("startTime") else ""
            end_time = data.get("endTime") if data.get("endTime") else ""
            with current_app.app_context():
                soft_obj = db.session.query(TbSoft) \
                    .filter(TbSoft.soft_id.like(f"%{soft_id}%") if soft_id else True) \
                    .filter(TbSoft.soft_name.like(f"%{soft_name}%") if soft_name else True) \
                    .filter(TbSoft.soft_version.like(f"%{soft_version}%") if soft_version else True) \
                    .filter(TbSoft.git_url.like(f"%{git_url}%") if git_url else True) \
                    .filter(TbSoft.official_url.like(f"%{official_url}%") if official_url else True) \
                    .filter(TbSoft.main_language.like(f"%{main_language}%") if main_language else True) \
                    .filter(TbSoft.languages.like(f"%{languages}%") if languages else True) \
                    .filter(TbSoft.created_at.between(start_time, end_time) if start_time and end_time else True)
                soft_list = soft_obj.paginate(page=current_page, per_page=per_page, error_out=True)
            result = to_dict(soft_list)
            return json.dumps({
                "code": 200,
                "msg": "success",
                "data": result,
                "page": {
                    "total": soft_list.total,
                    "pageNum": current_page,
                    "pageSize": per_page
                }
            }, indent=4, ensure_ascii=False)
        elif request.method == "GET":
            with current_app.app_context():
                soft_obj = db.session.query(TbSoft)
            result = to_dict(soft_obj)
            return json.dumps({
                "code": 200,
                "msg": "success",
                "data": result,
                "total": len(result)
            }, indent=4, ensure_ascii=False)

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(str(e))
        logger.error(e)
        return json.dumps({
            "code": 500,
            "msg": str(e),
            "data": ""
        }, indent=4, ensure_ascii=False)
    finally:
        db.session.close()


if __name__ == '__main__':
    # 这个要放main函数莉，放上面报错!
    app.register_blueprint(soft_blue, url_prefix='/soft')

    print(app.url_map)
    app.run(host="0.0.0.0", port=8088, debug=True, threaded=True)